﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Security;
using DevExpress.Persistent.BaseImpl.PermissionPolicy;
using DevExpress.Xpo;
using EasyXaf.ViewLayoutBuilder;
using System.ComponentModel;

namespace EasyXaf.Sample.Module.BusinessObjects;

[MapInheritance(MapInheritanceType.ParentTable)]
[DefaultProperty(nameof(UserName))]
[DetailViewLayoutBuilder]
public class ApplicationUser : PermissionPolicyUser, IObjectSpaceLink, ISecurityUserWithLoginInfo
{
    public static string BuildLayout()
    {
        return @$"
            <v>
                <p>{nameof(UserName)}</p>
                <t>
                    <v id='roles_tab' caption='角色' image='BO_Role'>
                        <p>{nameof(Roles)}</p>
                    </v>
                    <v caption='选项'>
                        <p>{nameof(ChangePasswordOnFirstLogon)}</p>
                        <p>{nameof(IsActive)}</p>
                    </v>
                </t>
            </v>
        ";
    }

    public ApplicationUser(Session session)
        : base(session)
    {
    }

    [Browsable(false)]
    [Aggregated, Association("User-LoginInfo")]
    public XPCollection<ApplicationUserLoginInfo> LoginInfo
    {
        get { return GetCollection<ApplicationUserLoginInfo>(nameof(LoginInfo)); }
    }

    IEnumerable<ISecurityUserLoginInfo> IOAuthSecurityUser.UserLogins => LoginInfo.OfType<ISecurityUserLoginInfo>();

    IObjectSpace IObjectSpaceLink.ObjectSpace { get; set; }

    ISecurityUserLoginInfo ISecurityUserWithLoginInfo.CreateUserLoginInfo(string loginProviderName, string providerUserKey)
    {
        ApplicationUserLoginInfo result = ((IObjectSpaceLink)this).ObjectSpace.CreateObject<ApplicationUserLoginInfo>();
        result.LoginProviderName = loginProviderName;
        result.ProviderUserKey = providerUserKey;
        result.User = this;
        return result;
    }
}
